package com.foreveross.proxyip.application.impl.monitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.proxyip.application.monitor.HistorySearchApplication;
import com.foreveross.proxyip.entity.ChannelEntity;
import com.foreveross.proxyip.entity.HistoryIpEntity;
import com.foreveross.proxyip.infra.PageData;
import com.foreveross.proxyip.monitor.domain.Channel;
import com.foreveross.proxyip.monitor.domain.HistorySearch;
import com.foreveross.proxyip.monitor.vo.HistoryIpEntityVO;

@Service
@Transactional
public class HistorySearchApplicationImpl implements HistorySearchApplication{
	private Channel channelDomain;//渠道领域
	private static List<ChannelEntity> channels;
	private static Map<String,String> channelsMap=new HashMap();
	@Override
	public PageData searchByConditions(HistoryIpEntityVO c,int pageIndex,int pageLen) throws Exception {
		// TODO Auto-generated method stub
		if(pageIndex<=0){
			pageIndex=PageData.DEFAULT_PAGEINDEX;
		}
		if(pageLen<=0){
			pageLen=PageData.DEFAULT_PAGELEN;
		}
		List<HistoryIpEntity> es=HistorySearch.searchByConditions(c, pageIndex, pageLen);
		long size=HistorySearch.searchSizeByConditions(c);
		//拼装成vo
		es=es==null?new ArrayList():es;
		List<Object> vos=new ArrayList();
		if(channels==null){
			channels=channelDomain.getAllChannels();
			for(ChannelEntity entity:channels){
				channelsMap.put(entity.getCode(), entity.getName());
			}
		}
		for(HistoryIpEntity e:es){
			HistoryIpEntityVO v=new HistoryIpEntityVO(e.getId(),e.getArea(),e.getCreateTime(),e.getIp()
					,e.getPort(),e.getResponseTime(),e.getRetrieveTime(),e.getState(),
					e.getRetrieveChannel(),channelsMap.get(e.getRetrieveChannel()));
			vos.add(v);
		}
		
		PageData p=new PageData();
		p.setDataSize(size);
		p.setPageIndex(pageIndex);
		p.setPageLen(pageLen);
		p.setResult(vos);
		int pageCount=(int)size/pageLen+((int)size%pageLen>0?1:0);
		p.setPageCount(pageCount);
		return p;
	}

}
